import { login, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          const token = response.headers.authorization
          setToken(token)
          commit('SET_TOKEN', token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    getUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          const res = response.data;
          if (res.status) {
            let roleArr = [],
              roleNameArr = [];            
            if (res.data.roles && res.data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              res.data.roles.forEach(item => {
                roleArr.push(item.engName);
                roleNameArr.push(item.name);
              })
              commit('SET_ROLES', roleNameArr)
            } else {
              roleArr = ['admin'];
              commit('SET_ROLES', roleArr)
            }
            res.data.roles = roleArr
            commit('SET_NAME', res.data.name)
            commit('SET_AVATAR', 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1532234362698&di=5d4a5555cdf01c57174f68270516fe5e&imgtype=0&src=http%3A%2F%2Fimg.bqatj.com%2Fimg%2Faf350d6710b8d2c3.jpg')
            resolve(res)
          } else {
            reject(res.message);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resolve()
        // logout(state.token).then(() => {
        //   commit('SET_TOKEN', '')
        //   commit('SET_ROLES', [])
        //   removeToken()
        //   resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user